package com.xxxy.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxy.commonResult.CommonResult;
import com.xxxy.commonResult.CommonResultPage;
import com.xxxy.dao.StudentDao;
import com.xxxy.log.Log;
import com.xxxy.model.Faculty;
import com.xxxy.model.Student;
import com.xxxy.response.StudentResponse;
import com.xxxy.service.FacultyService;
import com.xxxy.service.StudentService;
import com.xxxy.util.ExcelDemoUtils;
import com.xxxy.util.Md5EncryptUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;


/**
 * @author sjh
 * @date 2022/1/23 18:27
 */
@RestController
@Api(tags = "学生信息服务")
@RequestMapping("/student")
public class StudentController {

    @Autowired
    StudentService studentService;

    @Autowired
    FacultyService facultyService;

    private Consumer<List<Student>> batchInsert() {
        return students -> studentService.saveData(students);
    }

    @Log(module = "学生信息服务", description = "根据条件获取学生列表")
    @PostMapping(value = "/list")
    @ApiOperation(value = "学生列表")
//    @RequiresRoles(value={"ADMIN","TEACHER"},logical = Logical.OR)
    public CommonResult<CommonResultPage> list(@ApiParam("页数") @RequestParam(defaultValue = "1") Integer page,
                                               @ApiParam("一页条数") @RequestParam(defaultValue = "10") Integer size,
                                               @ApiParam("查询信息") @RequestBody(required = false) Student student) {
        return CommonResult.success(studentService.list(page, size, student));
    }

    @Log(module = "学生信息服务", description = "根据账号获取学生信息")
    @GetMapping(value = "/info/{account}")
    @ApiOperation(value = "单个学生信息")
    public CommonResult<StudentResponse> getInfoByAccount(@ApiParam("账号") @PathVariable String account) {
        return CommonResult.success(studentService.getByAccount(account));
    }

    @Log(module = "学生信息服务", description = "新增单个学生")
    @PostMapping(value = "/add")
    @ApiOperation(value = "新增单个学生")
//    @RequiresRoles(value={"ADMIN"})
    public CommonResult<Boolean> addStudent(@ApiParam("学生信息") @RequestBody Student student) {
        student.setPwd(Md5EncryptUtil.md5Encrypt(student.getAccount()));
        if (studentService.save(student)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @Log(module = "学生信息服务", description = "excel导入学生")
    @PostMapping(value = "/excelImport")
    @ApiOperation(value = "excel导入学生")
//    @RequiresRoles(value={"ADMIN"})
    public CommonResult<Boolean> excelImportStudents(MultipartFile multipartFile) throws IOException {
        try {
            AnalysisEventListener<Student> studentAnalysisEventListener = ExcelDemoUtils.getListener(this.batchInsert(), 10);
            EasyExcel.read(multipartFile.getInputStream(), Student.class, studentAnalysisEventListener).sheet().doRead();
            return CommonResult.success();
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @Log(module = "学生信息服务", description = "excel导出学生")
    @PostMapping(value = "/excelExport")
    @ApiOperation(value = "excel导出学生")
//    @RequiresRoles(value={"ADMIN"})
    public void excelExportStudents(HttpServletResponse response, @ApiParam("查询信息") @RequestBody(required = false) Student student) throws IOException {
        try {
            List<Student> list = studentService.list(student);
            String filename = URLEncoder.encode("studentExcel", "utf-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");
            /**
             *  EasyExcel的写文件操作，data()方法用来查询数据库数据返回list。
             * sheet为excel的工作表表名
             */
            EasyExcel.write(response.getOutputStream(), Student.class).sheet("sheet1").doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    @Log(module = "学生信息服务", description = "(批量)删除学生")
    @DeleteMapping(value = "/delete")
    @ApiOperation(value = "(批量)删除学生")
//    @RequiresRoles(value={"ADMIN"})
    public CommonResult<Boolean> deleteStudent(@ApiParam("学生账号数组") @RequestParam String[] accountArray) {
        if (studentService.deleteStudent(accountArray)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @Log(module = "学生信息服务", description = "更新学生信息")
    @PostMapping(value = "/update")
    @ApiOperation(value = "更新学生信息")
    @RequiresRoles(value = {"ADMIN"})
    public CommonResult<Boolean> updateByAccount(@ApiParam("学生信息") @RequestBody Student student) {
        if (studentService.updateById(student)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }
}
